package com.dailyblue.java.jdbc.pack0325.dao;

import com.dailyblue.java.jdbc.pack0325.bean.User;
import com.dailyblue.java.jdbc.pack0325.db.DBManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {
    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;

    public User login(String name,String password){
        User user = new User();
        String sql = "select u.*,floor(datediff(now(),birthday)/365) as 'age' from user u where name=? and password=md5(?)";
        try {
            conn = DBManager.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if(rs.next()){
                user.setId(rs.getInt(1));
                user.setName(rs.getString(2));
                user.setNickname(rs.getString(4));
                user.setGender(rs.getString(5));
                user.setBirthday(rs.getString(6));
                user.setAge(rs.getInt(7));
                return user;
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
